package com.yunnuo.monitor.job.manager;

import com.yunnuo.monitor.job.dao.IJobDao;
import com.yunnuo.monitor.job.entity.MonJob;
import com.yunnuo.monitor.job.service.IJobService;
import org.quartz.*;
import org.quartz.DateBuilder.IntervalUnit;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.quartz.Scheduler;


/**
 *
 *
 * @title: QuartzManager.java
 * @description: 计划任务管理
 *
 */
@Service
public class QuartzManager {

	private Scheduler scheduler;

	public QuartzManager(Scheduler scheduler){
		this.scheduler = scheduler;
	}
	@Autowired
	private IJobDao jobDao;

	/**
	 * 添加任务
	 *
	 * @param job
	 * @throws SchedulerException
	 */

	public void addJob(MonJob job) {
		try {
			Class jobClass = Class.forName(job.getMethod());
			// 创建jobDetail实例，绑定Job实现类
			// 指明job的名称，所在组的名称，以及绑定job类
			 JobDetail jobDetail = JobBuilder.newJob(jobClass) .withIdentity(job.getTaskName(), "gropu1").build();
			//  corn表达式
			 CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getOperation());
			//设置定时任务的时间触发规则
			  CronTrigger cronTrigger = TriggerBuilder.newTrigger().withIdentity(job.getTaskName(), "gropu1") .withSchedule(scheduleBuilder).build();
			// 把作业和触发器注册到任务调度中
			scheduler.scheduleJob(jobDetail,cronTrigger);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}


	/**
	 * 获取所有计划中的任务列表
	 *
	 * @return
	 * @throws SchedulerException
	 */
	public List<MonJob> getAllJob() throws SchedulerException {
		GroupMatcher<JobKey> matcher = GroupMatcher.anyJobGroup();
		Set<JobKey> jobKeys = scheduler.getJobKeys(matcher);
		List<MonJob> jobList = new ArrayList<MonJob>();
		for (JobKey jobKey : jobKeys) {
			List<? extends Trigger> triggers = scheduler.getTriggersOfJob(jobKey);
			for (Trigger trigger : triggers) {
				MonJob job = new MonJob();
				job.setTaskName(jobKey.getName());
				job.setParams("触发器:" + trigger.getKey());
				Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
				job.setStatus(triggerState.name());
				if (trigger instanceof CronTrigger) {
					CronTrigger cronTrigger = (CronTrigger) trigger;
					String cronExpression = cronTrigger.getCronExpression();
					job.setOperation(cronExpression);
				}
				jobList.add(job);
			}
		}
		return jobList;
	}

	/**
	 * 所有正在运行的job
	 *
	 * @return
	 * @throws SchedulerException
	 */
	public List<MonJob> getRunningJob() throws SchedulerException {
		List<JobExecutionContext> executingJobs = scheduler.getCurrentlyExecutingJobs();
		List<MonJob> jobList = new ArrayList<MonJob>(executingJobs.size());
		for (JobExecutionContext executingJob : executingJobs) {
			MonJob job = new MonJob();
			JobDetail jobDetail = executingJob.getJobDetail();
			JobKey jobKey = jobDetail.getKey();
			Trigger trigger = executingJob.getTrigger();
			job.setTaskName(jobKey.getName());
			job.setParams("触发器:" + trigger.getKey());
			Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
			job.setStatus(triggerState.name());
			if (trigger instanceof CronTrigger) {
				CronTrigger cronTrigger = (CronTrigger) trigger;
				String cronExpression = cronTrigger.getCronExpression();
				job.setOperation(cronExpression);
			}
			jobList.add(job);
		}
		return jobList;
	}

	/**
	 * 暂停一个job
	 *
	 * @param job
	 * @throws SchedulerException
	 */
	public void pauseJob(MonJob job) throws SchedulerException {
		JobKey jobKey = JobKey.jobKey(job.getTaskName(), "gropu1");
		scheduler.pauseJob(jobKey);
	}

	/**
	 * 恢复一个job
	 *
	 * @param job
	 * @throws SchedulerException
	 */
	public void resumeJob(MonJob job) throws SchedulerException {
		JobKey jobKey = JobKey.jobKey(job.getTaskName(),"gropu1");
		scheduler.resumeJob(jobKey);
	}

	/**
	 * 删除一个job
	 *
	 * @param job
	 * @throws SchedulerException
	 */
	public void deleteJob(MonJob job) throws SchedulerException {
		JobKey jobKey = JobKey.jobKey(job.getTaskName(),"grop1");
		scheduler.deleteJob(jobKey);

	}

	/**
	 * 立即执行job
	 *
	 * @param job
	 * @throws SchedulerException
	 */
	public void runAJobNow(MonJob job) throws SchedulerException {
		JobKey jobKey = JobKey.jobKey(job.getTaskName(), "grop1");
		scheduler.triggerJob(jobKey);
	}

	/**
	 * 更新job时间表达式
	 *
	 * @param job
	 * @throws SchedulerException
	 */
	public void updateJobCron(MonJob job) throws SchedulerException {

		TriggerKey triggerKey = TriggerKey.triggerKey(job.getTaskName(), "grop1");

		CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);

		CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getOperation());

		trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();

		scheduler.rescheduleJob(triggerKey, trigger);
	}

	/**
	 * 启动所有的定时任务
	 */
	public void startAllJob(){
	   List<MonJob> list =	this.jobDao.findAll();
		System.out.print(list.size());
	}

}